

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import subprocess
import os

class MyHandler(FileSystemEventHandler):
    def __init__(self, script_path):
        self.script_path = script_path
        subprocess.run(["/mnt/z/py-envs/xiaozhi/bin/python", self.script_path])

    def on_modified(self, event):
        if event.src_path.endswith(".py"):
            print(f"文件已修改: {event.src_path}")
            self.run_script()

    def run_script(self):
        print("重新运行脚本...")
        subprocess.run(["/mnt/z/py-envs/xiaozhi/bin/python", self.script_path])

if __name__ == "__main__":
    path_to_watch = "/home/thy/workspace/a.s/python"  # 监控当前目录
    script_to_run = "/home/thy/workspace/a.s/python/llm_lingyi_sev.py"  # 要运行的 Python 脚本
    event_handler = MyHandler(script_to_run)
    observer = Observer()
    observer.schedule(event_handler, path=path_to_watch, recursive=False)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

# import time
# import subprocess
# import psutil
# from watchdog.observers import Observer
# from watchdog.events import FileSystemEventHandler

# class MyHandler(FileSystemEventHandler):
#     def __init__(self, script_path):
#         self.script_path = script_path
#         self.process = None

#     def on_modified(self, event):
#         if event.src_path.endswith(".py"):
#             print(f"文件已修改: {event.src_path}")
#             self.run_script()

#     def run_script(self):
#         if self.process:
#             print("终止现有进程...")
#             self.process.kill()
#             self.process.wait()
#         print("正在运行脚本...")
#         self.process = subprocess.Popen(["/mnt/z/py-envs/xiaozhi/bin/python", self.script_path])

# def kill_process_on_port(port):
#     for proc in psutil.process_iter(['pid', 'name', 'connections']):
#         try:
#             for conn in proc.info['connections']:
#                 if conn.laddr.port == port:
#                     print(f"端口 {port} 被进程 {proc.info['pid']} 占用，正在终止...")
#                     proc.terminate()
#                     proc.wait()
#                     print(f"进程 {proc.info['pid']} 已终止")
#         except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
#             pass

# if __name__ == "__main__":
#     port_to_check = 50051
#     path_to_watch = "/home/thy/sock_workstation/python"  # 监控当前目录
#     script_to_run = "/home/thy/sock_workstation/python/grpc_llm_sev.py"  # 要运行的 Python 脚本

#     # 检查端口是否被占用，如果被占用则杀死相关进程
#     kill_process_on_port(port_to_check)

#     # 启动 Python 脚本
#     event_handler = MyHandler(script_to_run)
#     observer = Observer()
#     observer.schedule(event_handler, path=path_to_watch, recursive=False)
#     observer.start()

#     # 在启动时直接运行脚本
#     event_handler.run_script()

#     try:
#         while True:
#             time.sleep(1)
#     except KeyboardInterrupt:
#         observer.stop()
#         if event_handler.process:
#             print("终止现有进程...")
#             event_handler.process.terminate()
#             event_handler.process.wait()
#     observer.join()


# import time
# import subprocess
# import os
# import psutil
# from watchdog.observers import Observer
# from watchdog.events import FileSystemEventHandler

# class MyHandler(FileSystemEventHandler):
#     def __init__(self, script_path):
#         self.script_path = script_path
#         self.process = None

#     def on_modified(self, event):
#         if event.src_path.endswith(".py"):
#             print(f"文件已修改: {event.src_path}")
#             self.run_script()

#     def run_script(self):
#         if self.process:
#             print("终止现有进程...")
#             self.process.kill()
#             self.process.wait()
#         print("重新运行脚本...")
#         self.process = subprocess.Popen(["/mnt/z/py-envs/xiaozhi/bin/python", self.script_path])

# def kill_process_on_port(port):
#     for proc in psutil.process_iter(['pid', 'name']):
#         try:
#             # 获取进程的连接信息
#             connections = proc.net_connections()
#             for conn in connections:
#                 if conn.laddr.port == port:
#                     print(f"端口 {port} 被进程 {proc.info['pid']} 占用，正在终止...")
#                     proc.terminate()
#                     proc.wait()
#                     print(f"进程 {proc.info['pid']} 已终止")
#         except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
#             pass

# if __name__ == "__main__":
#     port_to_check = 50051
#     path_to_watch = "/home/thy/sock_workstation/python"  # 监控当前目录
#     script_to_run = "/home/thy/sock_workstation/python/grpc_llm_sev.py"  # 要运行的 Python 脚本

#     # 检查端口是否被占用，如果被占用则杀死相关进程
#     kill_process_on_port(port_to_check)

#     # 启动 Python 脚本
#     event_handler = MyHandler(script_to_run)
#     observer = Observer()
#     observer.schedule(event_handler, path=path_to_watch, recursive=False)
#     observer.start()

#     try:
#         while True:
#             time.sleep(1)
#     except KeyboardInterrupt:
#         observer.stop()
#         if event_handler.process:
#             print("终止现有进程...")
#             event_handler.process.terminate()
#             event_handler.process.wait()
#     observer.join()

# import time
# import subprocess
# import os
# import psutil
# from watchdog.observers import Observer
# from watchdog.events import FileSystemEventHandler

# class MyHandler(FileSystemEventHandler):
#     def __init__(self, script_path):
#         self.script_path = script_path
#         self.process = None

#     def on_modified(self, event):
#         if event.src_path.endswith(".py"):
#             print(f"文件已修改: {event.src_path}")
#             self.run_script()

#     def run_script(self):
#         if self.process:
#             print("终止现有进程...")
#             self.process.kill()
#             self.process.wait()
#         print("重新运行脚本...")
#         self.process = subprocess.Popen(["/mnt/z/py-envs/xiaozhi/bin/python", self.script_path])

# def kill_process_on_port(port):
#     for proc in psutil.process_iter(['pid', 'name', 'connections']):
#         try:
#             for conn in proc.info['connections']:
#                 if conn.laddr.port == port:
#                     print(f"端口 {port} 被进程 {proc.info['pid']} 占用，正在终止...")
#                     proc.terminate()
#                     proc.wait()
#                     print(f"进程 {proc.info['pid']} 已终止")
#         except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
#             pass

# if __name__ == "__main__":
#     port_to_check = 50051
#     path_to_watch = "/home/thy/sock_workstation/python"  # 监控当前目录
#     script_to_run = "/home/thy/sock_workstation/python/grpc_llm_sev.py"  # 要运行的 Python 脚本

#     # 检查端口是否被占用，如果被占用则杀死相关进程
#     kill_process_on_port(port_to_check)

#     # 启动 Python 脚本
#     event_handler = MyHandler(script_to_run)
#     observer = Observer()
#     observer.schedule(event_handler, path=path_to_watch, recursive=False)
#     observer.start()

#     try:
#         while True:
#             time.sleep(1)
#     except KeyboardInterrupt:
#         observer.stop()
#         if event_handler.process:
#             print("终止现有进程...")
#             event_handler.process.terminate()
#             event_handler.process.wait()
#     observer.join()
